package com.lst.servlet;

import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.druid.util.StringUtils;
import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.entity.request.DynamicReqPara;
import com.lst.entity.response.DynamicResPara;
import com.lst.model.Dynamic;
import com.lst.model.JiluLog;
import com.lst.service.ClientNumService;
import com.lst.service.DynamicService;
import com.lst.service.JiluLogService;
import com.lst.service.MstDiscussService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.RequestUtils;


/**
 * @ClassName: DynamicDetailServlet
 * @Description: 动态详情接口
 */
public class DynamicDetailServlet extends BaseServlet {

	/**
	 * @Fields serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	private DynamicService dynamicService = ctx.getBean(DynamicService.class);
	
	private ClientNumService clientNumService = ctx.getBean(ClientNumService.class);
	
	private MstDiscussService mstDiscussService = ctx.getBean(MstDiscussService.class);
	
	private JiluLogService jiluLogService = ctx.getBean(JiluLogService.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		DynamicResPara resPara = new DynamicResPara();

		try {
			DynamicReqPara reqPara = getReqPara(request);
		
		if(isCheckField(reqPara,resPara)){
			Integer dynamicId = Integer.valueOf(reqPara.getDynamicId());	
			Integer userid = Integer.valueOf(reqPara.getUserid());	
			
			Dynamic dynamic=dynamicService.selectByPrimaryKey(dynamicId);
			if(dynamic!=null){
				//收藏量
				Integer favoriteNum = CommFunUtils.opNum(null, dynamic.getDynamicId(), CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC, CommCode.SYSTEM_COUNT_FAVORITE, clientNumService);
				//分享量
				Integer shareNum = CommFunUtils.opNum(null, dynamic.getDynamicId(), CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC, CommCode.SYSTEM_COUNT_SHARE, clientNumService);
				dynamic.setFavoriteNum(favoriteNum);
				dynamic.setShareNum(shareNum);
				
				//转化时间戳
				 Date date=dynamic.getCreatedate();
				 Long createDate2=date.getTime();
				 dynamic.setCreatedate2(createDate2);
				 
					//计算图片宽高
					if (dynamic.getDynamicUrl()!= null && dynamic.getDynamicUrl()!= "") {
							String[] strs = dynamic.getDynamicUrl().split(",");
							int[] widths = new int[strs.length];
							int[] heights = new int[strs.length];

							for (int i = 0; i < strs.length; i++) {
								InputStream is = null;
								BufferedImage src = null;
								try {
									is = new FileInputStream(CommCode.readUrl + strs[i].substring(13));
									src = javax.imageio.ImageIO.read(is);
									widths[i] = src.getWidth(); // 得到源图宽
									heights[i] = src.getHeight(); // 得到源图高
									is.close();
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
							dynamic.setWidth(widths);
							dynamic.setHeight(heights);
					}
				
				//标识是否收藏
				Map<String, Object> fmap = new HashMap<String, Object>();
				fmap.put("enabled", true);
				fmap.put("isdeleted", false);
				fmap.put("clientid", userid);
				fmap.put("actid", dynamic.getDynamicId());
				fmap.put("acttype", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
				fmap.put("numtype", CommCode.SYSTEM_COUNT_FAVORITE);
				Integer count = clientNumService.queryCountByMap(fmap);
				if(count>0){
					dynamic.setIsFavorite(true);
				}else{
					dynamic.setIsFavorite(false);
				}
				
				Map<String, Object> dymap = new HashMap<String, Object>();
				dymap.put("enabled", true);
				dymap.put("isDeleted", false);
				dymap.put("tarid",dynamicId );
				dymap.put("type", CommCode.SYSTEM_CARESEL_RANGE_DYNAMIC);
	            //评论数量
				Integer discussNum = mstDiscussService.queryCountByMap(dymap);
	            dynamic.setDiscussNum(discussNum);
	            
	            //喜欢数量
	            Map<String, Object> mapjl = new HashMap<String, Object>();
	            mapjl.put("sourceId", dynamicId);
	            mapjl.put("jiluType", 1);
				int loveNum=jiluLogService.countBySourceId(mapjl);
				dynamic.setLoveNum(loveNum);
				
				//喜欢标识
				Map<String, Object> jilumap = new HashMap<String, Object>();
				jilumap.put("jiluType", 1);
				jilumap.put("isDelete", false);
				jilumap.put("sourceId", dynamicId);
				jilumap.put("createUser", userid);
				JiluLog jilu=jiluLogService.queryByMap(jilumap);
				if(jilu!=null){
					dynamic.setIsLove(jilu.getIsLove());
				}else{
					dynamic.setIsLove(false);
				}
				
				//对该动态喜欢的所有人详情
				Map<String, Object> jlmap = new HashMap<String, Object>();
				jlmap.put("jiluType", 1);
				jlmap.put("isDelete", false);
				jlmap.put("isLove", true);
				jlmap.put("sourceId", dynamicId);
				jlmap.put("orderByClause", "md.createDate desc");
				PageBounds pagebounds = new PageBounds(1,6);
				List<JiluLog> jiluList=jiluLogService.queryByList(jlmap, pagebounds);
				
				resPara.setDynamic(dynamic);
				resPara.setJiluLogList(jiluList);
				resPara.setCode(CommCode.M_Y000000);
				resPara.setMessage(CommCode.M_Y000001);
			}else{
				resPara.setCode(CommCode.M_A000001);
            	resPara.setMessage(CommCode.M_A000002);
		  }
			
		  }
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}
		
		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);
	//		logger.info("DynamicDetailServlet jsonResult:" + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

	//		logger.info("doPost end run(s): " + DateUtil.calLastedTime(startDate));
		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public DynamicReqPara getReqPara(HttpServletRequest request) {

		DynamicReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new DynamicReqPara());

			reqPara = (DynamicReqPara) baseRequest.clone();

			String dynamicId = request.getParameter("dynamicId");
			String userid = request.getParameter("userid");

//			logger.info("reqPara dynamicId:" + dynamicId);
//			logger.info("reqPara userid:" + userid);

            reqPara.setDynamicId(dynamicId);
            reqPara.setUserid(userid);

		} catch (Exception e) {
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		DynamicReqPara cdReqPara = (DynamicReqPara) reqPara;
		BaseResponse cdResPara = (BaseResponse) resPara;

		if (StringUtils.isEmpty(cdReqPara.getDynamicId())) {
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage("动态id为空");
		}else if(StringUtils.isEmpty(cdReqPara.getUserid())){
			cdResPara.setCode(CommCode.M_A000000);
			cdResPara.setMessage(CommCode.M_P000002);
		}else {
			flag = true;
		}

		return  flag;
	}

}
